package cordova.plugin.zmq;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.text.Html;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author mj
 *         created at 2016/6/14
 */
public class ShowNotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        String msg = intent.getStringExtra("message");
        Log.i("NotificationReceiver", msg);
        try {
            JSONObject jsonObject = new JSONObject(msg);
            JSONObject jsonObject1 = new JSONObject(jsonObject.getString("message"));
            JSONObject js = new JSONObject(jsonObject1.getString("body"));
            String title = js.getString("title");
            String content = js.getString("content");
            if (content != null && title != null) {
                int iconResID = context.getResources().getIdentifier("icon", "drawable", context.getPackageName());
                Intent broadcastIntent = new Intent(context, ZMQPluginBroadcastReceiver.class);
                broadcastIntent.setAction(ZMQPluginBroadcastReceiver.ACTION);
                broadcastIntent.putExtra("msg", msg);
                int id = (int) (Math.random() * 65000);
                PendingIntent pendingIntent = PendingIntent.
                        getBroadcast(context, id, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
                builder.setContentTitle(title)
                        .setContentText(Html.fromHtml(content))
                        .setDefaults(Notification.DEFAULT_ALL) //设置默认铃声，震动等
                        .setSmallIcon(iconResID)
                        .setContentIntent(pendingIntent)
                        .setVibrate(new long[]{100, 400, 100, 400})
                        .setAutoCancel(true)
                        .setOngoing(true)
                        .setWhen(System.currentTimeMillis());
                NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                manager.notify(id, builder.build());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}
